﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using CoolCode.Entities;
using CoolCode.Services;
using CoolCode.Web;
using CoolCode.Linq;

namespace CoolCode.Web.UI.Views.Admin
{
    public partial class Users : SearchPage<aspnet_Membership, IMembershipService>
    {
        //private IMenuService _MenuService;
        //public IMenuService MenuService
        //{
        //    get
        //    {
        //        if (_MenuService == null)
        //        {
        //            _MenuService = ServiceFactory.Produce<IMenuService>();
        //        }
        //        return _MenuService;
        //    }
        //}

        protected void Page_Load(object sender, EventArgs e)
        {
            gvMaster.DisableCommand(this.Role);
            gvMaster.RowDeleting += new GridViewDeleteEventHandler(gvMaster_RowDeleting);
            gvMaster.RowEditing += new GridViewEditEventHandler(gvMaster_RowEditing);
            lnkBack.Click += new EventHandler(lnkBack_Click);

            lnkSave.Click += new EventHandler(lnkSave_Click);
            new string[] { "chkRead", "chkWrite", "chkDelete", "chkExport" }
                .ForEach(c => gvEntry.HandleSelectAll(c + "SelectAll", c));
            //menuInUsers.Closing += new EventHandler(menuInUsers_Closing);

            this.Setup(lnkSearch, pgrMaster, c =>
            {
                gvMaster.DataSource = c.Result;
                gvMaster.DataBind();
                pgrMaster.Bind(c.Result);
                udpHeader.Update();
            },
            c =>
            {
                udpHeader.Alert(c.Exception);
            });

            if (!IsPostBack)
            {
                lstRole.Bind(Roles.GetAllRoles());
            }
        }

        protected void lnkBack_Click(object sender, EventArgs e)
        {
            mvwMain.ActiveViewIndex = 0;
            udpHeader.Update();
        }

        //protected void menuInUsers_Closing(object sender, EventArgs e)
        //{
        //    mvwMain.ActiveViewIndex = 0;
        //    this.Search(pgrMaster.PageIndex);
        //}

        protected void gvMaster_RowEditing(object sender, GridViewEditEventArgs e)
        {
            mvwMain.ActiveViewIndex = 1;
            Label lblUserName = gvMaster.Rows[e.NewEditIndex].FindControl<Label>("lblUserName");
            string key = lblUserName.Text;
            //menuInUsers.Show(key);
            //udpHeader.Update();
            lblDspUser.Text = key;
            gvEntry.DataSource = this.MenuService.ListMenuInUser(key);
            gvEntry.DataBind();

            string[] roles = Roles.GetRolesForUser(key);
            lstRole.SetSelections(roles);
            udpEntry.Update();
        }

        protected void lnkSave_Click(object sender, EventArgs e)
        {
            MembershipUser user = Membership.GetUser(lblDspUser.Text);
            if (user == null)
            {
                udpHeader.Alert("用户名不存在或者用户已经被删除！");
                return;
            }
            List<RoleView> list = new List<RoleView>();
            foreach (GridViewRow gvr in gvEntry.Rows)
            {
                RoleView entity = new RoleView
                {
                    MenuID = gvEntry.GetKey<int>(gvr.RowIndex),
                    BelongTo = user.UserName,
                    CanRead = gvr.IsSelected("chkRead"),
                    CanWrite = gvr.IsSelected("chkWrite"),
                    CanDelete = gvr.IsSelected("chkDelete"),
                    CanExport = gvr.IsSelected("chkExport"),
                };
                list.Add(entity);
            }
            Log log = this.BuildLog(UserAction.Edit, lblDspUser.Text);
            this.MenuService.SaveMenuInUser(list, log);
            string[] roles = lstRole.GetSelections().ToArray();
            Roles.AddUserToRoles(user.UserName, roles);
            udpHeader.Alert("操作成功！");
            //OnClosing();
            mvwMain.ActiveViewIndex = 0;
            this.Search(pgrMaster.PageIndex);
        }

        public override IQueryBuilder<aspnet_Membership> CreateFilter()
        {
            return QueryBuilder.Create<aspnet_Membership>()
                .Like(c => c.aspnet_User.UserName, txtUser.Text);
        }

        protected void gvMaster_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //GridView grid = (GridView)sender;
            //string key = grid.GetKey<string>(e.RowIndex);
            Label lblUserName = gvMaster.Rows[e.RowIndex].FindControl<Label>("lblUserName");
            string key = lblUserName.Text;
            Service.DeleteUser(key, true);
            Log log = this.BuildLog(UserAction.Delete, key);
            MenuService.DeleteMenuInUser(key, log);
            this.Search(pgrMaster.PageIndex);
        }
    }
}
